﻿using System.Collections.Generic;
using CNF.Common.Base.SimpleOrm.Data;
using CNF.Common.Base.SimpleOrm.DataBaseProvidrer;
using CNF.Common.Base.SimpleOrm.Domain;
using CNF.Common.Base.SimpleOrm.Entities;
using PetaPoco;

namespace CNF.Common.Base.SimpleOrm.ServiceProxyies
{
    public abstract class BaseViewServiceProxy<DataKeyType, EntityType, DataServiceType, DomainType> : IViewServiceProxy<DataKeyType, EntityType, DataServiceType, DomainType>
        where DataKeyType : struct
        where EntityType : BaseEnity<DataKeyType>, new()
        where DataServiceType : BaseDataService<DataKeyType, EntityType>
        where DomainType : BaseDomain, new()
    {
        protected IDataBaseStoreage<Database> dataBaseStoreage;
        protected string dataBaseKey;
        protected IServiceContainer serviceContainer;

        protected BaseViewServiceProxy(IDataBaseStoreage<Database> dataBaseStoreage, string dataBaseKey, IServiceContainer serviceContainer)
        {
            this.dataBaseStoreage = dataBaseStoreage;
            this.dataBaseKey = dataBaseKey;
            this.serviceContainer = serviceContainer;
        }
 
        private Database CurrentDatabase
        {
            get { return dataBaseStoreage.GetCurentDataBaseByKey(dataBaseKey); }
        }

        protected ITransaction CurrentTransaction
        {
            get { return this.CurrentDatabase.GetTransaction(); }
        }

        protected abstract DataServiceType CurrentDataService { get; }
 
        public DomainType LoadByID(DataKeyType dataKey)
        {
            return ConvertToDomain(CurrentDataService.LoadByID(dataKey));
        }

        protected abstract DomainType ConvertToDomain(EntityType dbEntity);

        protected abstract List<DomainType> ConvertToDomainList(List<EntityType> dbEntities);

        public bool Exists(object primaryKey)
        {
            return Exists(primaryKey);
        }

        public List<DomainType> QueryAll()
        {
            return ConvertToDomainList(CurrentDataService.QueryAll());
        }
    }
}
